<template>
  <div class="app-container">
    <ContentWrap style="padding: 0 !important;">
      <el-row :gutter="10">
        <!--        <div style="position: absolute;bottom: 8px;left: 8px;height: calc(100% - 80px);z-index: 1000;color: #FFFFFF;">-->
        <el-col :span="7" v-if="lineFormVisible || pointFormVisible" :style="getAvailableHeight">
          <el-card style="height: 100%;" :body-style="{padding: '10px'}" v-show="pointFormVisible">
            <div slot="header" class="clearfix">
              <span>节点详情</span>
              <div style="float: right; padding: 3px 0;">
                <el-button type="text" @click="saveGistPointInfo">保存</el-button>
                <el-button style="color: #FF0000;" type="text" @click="handlePointClose">关闭</el-button>
              </div>
            </div>

            <div :style="sidebar.opened ? 'width: 460px' : 'width: 500px'">
              <el-form ref="refPointForm" :model="pointForm" :rules="pointFormRules" label-width="80px" size="mini">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设施类别" prop="SCODE">
                      <el-select v-model="pointForm.SCODE" placeholder="请选择">
                        <el-option v-for="dict in dictTypes['scode_type']"
                                   :key="dict.value"
                                   :label="dict.label"
                                   :value="dict.value"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="点号" prop="EXP_NO">
                      <el-input v-model="pointForm.EXP_NO" placeholder="请输入" readonly/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设施编号" prop="PNO">
                      <el-input v-model="pointForm.PNO" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="设施名称" prop="FEATURE">
                      <el-input v-model="pointForm.FEATURE" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="位置" prop="ADDRESS">
                      <el-input v-model="pointForm.ADDRESS" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="材质" prop="METERIAL">
                      <el-select v-model="pointForm.METERIAL" placeholder="请选择">
                        <el-option v-for="dict in dictTypes['material_type']"
                                   :key="dict.value"
                                   :label="dict.label"
                                   :value="dict.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="规格" prop="SPEC">
                      <el-input v-model="pointForm.SPEC" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="埋深(米)" prop="DEEP">
                      <el-input-number style="width: 100%;" :precision="2" :step="0.1" v-model="pointForm.DEEP"
                                       placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="高程(米)" prop="H">
                      <el-input-number style="width: 100%;" :precision="2" :step="0.1" v-model="pointForm.H"
                                       placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="X坐标" prop="X">
                      <el-input v-model="pointForm.X" placeholder="请输入" readonly/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="Y坐标" prop="Y">
                      <el-input v-model="pointForm.Y" placeholder="请输入" readonly/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="旋转角度" prop="ROTANG">
                      <el-input-number style="width: 100%;" :step="1" v-model="pointForm.ROTANG"
                                       placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="建设日期" prop="MDATE">
                      <el-date-picker clearable
                                      v-model="pointForm.MDATE"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      style="width: 100%;"
                                      placeholder="请选择">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所在道路" prop="ROAD">
                      <el-input v-model="pointForm.ROAD" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="开关状态" prop="ONOFF">
                      <el-radio-group v-model="pointForm.ONOFF" placeholder="请选择">
                        <el-radio label="1">开启</el-radio>
                        <el-radio label="0">关闭</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="设施状态" prop="STAURS">
                      <el-radio-group v-model="pointForm.STAURS" placeholder="请选择">
                        <el-radio :label="0">有效</el-radio>
                        <el-radio :label="1">失效</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="详情" prop="DETAIL">
                      <el-input v-model="pointForm.DETAIL" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="闸门种类" prop="KIND">
                      <el-input v-model="pointForm.KIND" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="井深(米)" prop="WDEEP">
                      <el-input-number style="width: 100%;" :precision="2" :step="0.1" v-model="pointForm.WDEEP"
                                       placeholder="请输入井深"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="钥匙型号" prop="KEYTYPE">
                      <el-input style="width: 100%;" v-model="pointForm.KEYTYPE" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="路面类型" prop="ROADTYPE">
                      <el-input style="width: 100%;" v-model="pointForm.ROADTYPE" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="生产厂家" prop="MAKER">
                      <el-input style="width: 100%;" v-model="pointForm.MAKER" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="入库日期" prop="SUR_DATE">
                      <el-date-picker clearable
                                      v-model="pointForm.SUR_DATE"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      style="width: 100%;"
                                      placeholder="请选择">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="更新日期" prop="DB_DATE">
                      <el-date-picker clearable
                                      v-model="pointForm.DB_DATE"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      style="width: 100%;"
                                      placeholder="请选择">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="工程号" prop="P_ID">
                      <el-input v-model="pointForm.P_ID" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="图幅号" prop="MAPNUMBER">
                      <el-input v-model="pointForm.MAPNUMBER" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span=" 24
                      ">
                    <el-form-item label="备注" prop="REMARK">
                      <el-input v-model="pointForm.REMARK" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-card>

          <el-card style="height: 100%;" :body-style="{padding: '10px'}" v-show="lineFormVisible">
            <div slot="header" class="clearfix">
              <span>管线详情</span>
              <div style="float: right; padding: 3px 0;">
                <el-button type="text" @click="savePolylineData">保存</el-button>
                <el-button style="color: #FF0000;" type="text" @click="handlePolylineClose">关闭</el-button>
              </div>
            </div>

            <div :style="sidebar.opened ? 'width: 460px' : 'width: 500px'">
              <el-form ref="refLineForm" :model="lineForm" :rules="lineFormRules" label-width="110px" size="mini">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="起点编号" prop="S_POINT">
                      <el-input v-model="lineForm.S_POINT" placeholder="请输入" readonly/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="终点编号" prop="E_POINT">
                      <el-input v-model="lineForm.E_POINT" placeholder="请输入" readonly/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="管径" prop="D_S">
                      <el-select size="mini" v-model="lineForm.D_S" placeholder="请选择">
                        <el-option v-for="dict in dictTypes['caliber_type']"
                                   :key="dict.value"
                                   :label="dict.label"
                                   :value="dict.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="材质" prop="MATERIAL">
                      <el-select v-model="lineForm.MATERIAL" placeholder="请选择">
                        <el-option v-for="dict in dictTypes['material_type']"
                                   :key="dict.value"
                                   :label="dict.label"
                                   :value="dict.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="所在道路" prop="ROAD">
                      <el-input v-model="lineForm.ROAD" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="地址" prop="ADDRESS">
                      <el-input v-model="lineForm.ADDRESS" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row v-if="!lineForm.id">
                  <el-col :span="12">
                    <el-form-item label="起点设施类别" prop="S_SCODE">
                      <el-select v-model="lineForm.S_SCODE" placeholder="请选择">
                        <el-option v-for="dict in dictTypes['scode_type']"
                                   :key="dict.value"
                                   :label="dict.label"
                                   :value="dict.value"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="终点设施类别" prop="E_SCODE">
                      <el-select v-model="lineForm.E_SCODE" placeholder="请选择">
                        <el-option v-for="dict in dictTypes['scode_type']"
                                   :key="dict.value"
                                   :label="dict.label"
                                   :value="dict.value"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="起点埋深(米)" prop="S_DEEP">
                      <el-input-number style="width: 100%;" :precision="2" :step="0.1" v-model="lineForm.S_DEEP"
                                       placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="终点埋深(米)" prop="E_DEEP">
                      <el-input-number style="width: 100%;" :precision="2" :step="0.1" v-model="lineForm.E_DEEP"
                                       placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item
                      label="流向"
                      prop="FLOW_D">
                      <el-radio-group v-model="lineForm.FLOW_D" placeholder="请选择">
                        <el-radio :label="1">起点 → 终点</el-radio>
                        <el-radio :label="0">终点 → 起点</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="管线长度(米)" prop="LLENGTH">
                      <el-input-number style="width: 100%;" :precision="2" :step="0.1" v-model="lineForm.LLENGTH"
                                       placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="工程号" prop="P_ID">
                      <el-input v-model="lineForm.P_ID" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="建设日期" prop="MDATE">
                      <el-date-picker clearable
                                      v-model="lineForm.MDATE"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      style="width: 100%;"
                                      placeholder="请选择">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="验收日期" prop="CDATE">
                      <el-date-picker clearable
                                      v-model="lineForm.CDATE"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      style="width: 100%;"
                                      placeholder="请选择">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="详情" prop="DETAIL">
                      <el-input v-model="lineForm.DETAIL" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="入库日期" prop="SUR_DATE">
                      <el-date-picker clearable
                                      v-model="lineForm.SUR_DATE"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      style="width: 100%;"
                                      placeholder="请选择">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="更新日期" prop="DB_DATE">
                      <el-date-picker clearable
                                      v-model="lineForm.DB_DATE"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      style="width: 100%;"
                                      placeholder="请选择">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="备注" prop="REMARK">
                      <el-input v-model="lineForm.REMARK" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-card>
          <!--        </div>-->
        </el-col>

        <el-col :span="lineFormVisible || pointFormVisible? 17 : 24">
          <div style="width: 100%;" :style="getAvailableHeight">
            <L7Map @mapLoaded="handleMapLoaded" :zoom="13">
              <div
                style="position: absolute;top: 8px;right: 8px;z-index: 1000;display: flex;justify-content: space-between;">
                <div class="custom-button-group-box">
                  <el-dropdown :hide-on-click="false" class="right-menu-item hover-effect" trigger="click"
                               style="color: #FFFFFF !important;">
                    <el-tooltip content="吸附开关" placement="top" effect="light">
                      <div class="custom-button-box">
                        <i class="el-icon-link"></i>
                      </div>
                    </el-tooltip>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item><span style="color: rgb(24, 144, 255);">作用：绘制时吸附到附近的管点</span>
                      </el-dropdown-item>

                      <el-dropdown-item divided>
                        <div style="width: 240px;display: flex;justify-content: space-between;align-items: center;">
                          <div>吸附开关</div>
                          <div>
                            <el-switch v-model="adsorbEnable"
                                       active-color="#13ce66"
                                       inactive-color="#ff4949"
                                       active-text="开"
                                       inactive-text="关">
                            </el-switch>
                          </div>
                        </div>
                      </el-dropdown-item>

                      <el-dropdown-item divided>
                        <div style="width: 240px;display: flex;justify-content: space-between;align-items: center;">
                          <div>吸附方向</div>
                          <div>
                            <el-switch v-model="adsorbBeginning"
                                       active-color="#13ce66"
                                       inactive-color="#ff4949"
                                       active-text="起点"
                                       inactive-text="终点">
                            </el-switch>
                          </div>
                        </div>
                      </el-dropdown-item>

                      <el-dropdown-item divided>
                        <div style="width: 240px;display: flex;justify-content: space-between;align-items: center;">
                          <div>吸附范围({{ adsorbRange }}米)</div>
                          <div style="width: 130px;">
                            <el-slider v-model="adsorbRange" :min="1" :max="5"></el-slider>
                          </div>
                        </div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <div class="custom-button-divider"></div>
                  <div class="custom-button-box" @click="handleDrawPointClick">
                    <svg-icon icon-class="draw-point"></svg-icon>
                  </div>
                  <div class="custom-button-divider"></div>
                  <div class="custom-button-box" @click="handleDrawLineClick">
                    <svg-icon icon-class="draw-line"></svg-icon>
                  </div>
                  <div class="custom-button-divider" v-if="editingFeature"></div>
                  <div class="custom-button-box" v-if="editingFeature"
                       @click="handleDeleteClick">
                    <i class="el-icon-delete"></i>
                  </div>
                  <div class="custom-button-divider"></div>
                  <div class="custom-button-box" @click="toggleLegendControl">
                    <el-tooltip :content="legendControlVisible?'隐藏图例':'显示图例'" placement="top" effect="light">
                      <i class="el-icon-s-flag"></i>
                    </el-tooltip>
                  </div>
                  <div class="custom-button-divider"></div>
                  <div class="custom-button-box" @click="layerPanelVisible = !layerPanelVisible">
                    <el-tooltip :content="layerPanelVisible?'隐藏图层':'显示图层'" placement="top" effect="light">
                      <i class="el-icon-copy-document"></i>
                    </el-tooltip>
                  </div>
                </div>
              </div>

              <div v-show="layerPanelVisible"
                   style="position: absolute;bottom: 8px;right: 8px;height: calc(100% - 50px);z-index: 1000;color: #FFFFFF;">
                <el-card style="min-width: 240px;max-width:300px;height: 100%;">
                  <el-scrollbar style="height: 95%;">
                    <el-tree :data="layerTreeData"
                             v-loading="layerTreeLoading"
                             show-checkbox
                             ref="refLayerTree"
                             node-key="name"
                             highlight-current
                             default-expand-all
                             :default-checked-keys="defaultCheckTreeData"
                             @check-change="handleNodeChange">
                      <template slot-scope="{ node, data }">
                        <div v-if="data.icon" style="display: flex;align-items: center;">
                          <img :src="getLayerNodeImage(data)" alt=""
                               style="width: 16px;height: 16px;margin-right: 5px;">
                          <span style="font-size: 12px;">{{ data.name }}</span>
                          <span style="font-size: 12px;">{{ data.count ? `(${data.count})` : '' }}</span>
                        </div>
                        <div v-else>
                          <span style="font-size: 12px;">{{ data.name }}</span>
                          <span style="font-size: 12px;">{{ data.count ? `(${data.count})` : '' }}</span>
                        </div>
                      </template>
                    </el-tree>
                  </el-scrollbar>
                </el-card>
              </div>
            </L7Map>
          </div>
        </el-col>
      </el-row>
    </ContentWrap>
  </div>
</template>

<script>
import * as turf from '@turf/turf'
import L7Map from "@/components/L7Maps/map.vue";
import {DrawPoint, DrawLine, DrawEvent} from '@antv/l7-draw';
import {
  loadFeaturesByWFS,
  initSceneZoomControl,
  initSceneLegendControl,
  initSceneImage,
  initPointLayer,
  initMapLayerTree,
  callSQLViewByWFS,
  initLineLabelLayer
} from '@/utils/wfsUtil'
import {drawWmsLayer} from '@/components/L7Maps/util'
import {
  findTableData,
  delTableData,
  addPointTableData,
  updatePointTableData,
  addLineTableData,
  updateLineTableData
} from '@/api/leakage/pgedit'
import {LineLayer, PointLayer} from "@antv/l7";

import {mapGetters} from 'vuex'

export default {
  name: 'PipeNetworkDraw',
  components: {L7Map},
  data() {
    return {
      dictTypes: {
        'caliber_type': [],
        'material_type': [],
        'scode_type': []
      },
      // 屏幕高度
      screenHeight: null,
      // 地图场景对象
      mapScene: undefined,
      // 图例控件
      legendControl: undefined,
      // 图例控件是否可见
      legendControlVisible: true,
      // 图层面板是否可见
      layerPanelVisible: true,
      // 图层树数据
      layerTreeData: [],
      // 图层树数据加载中
      layerTreeLoading: true,
      // 图层树默认选中节点数据
      defaultCheckTreeData: [],
      // 管线图层
      polylineLayer: undefined,
      // 管线文本标记图层
      polylineLabelLayer: undefined,
      // 管点图层
      pointLayerList: [],
      // 绘制管线工具
      drawLineTool: undefined,
      // 当前正在绘制管线
      isDrawingLine: false,
      // 绘制点工具
      drawPointTool: undefined,
      // 当前正在绘制点
      isDrawingPoint: false,
      // 吸附开关
      adsorbEnable: true,
      // 吸附方向：true吸附起点，false吸附终点
      adsorbBeginning: true,
      // 吸附范围：米
      adsorbRange: 3,
      // 选中管线时显示的图层
      activePolylineLayer: undefined,
      // 选中管线时显示的图层是否添加到地图场景
      activePolylineLayerAdded: false,
      // 选中管点时显示的图层
      activePointLayer: undefined,
      // 选中管点时显示的图层是否添加到地图场景
      activePointLayerAdded: false,
      // 编辑中的要素
      editingFeature: undefined,
      // 管点表单
      pointForm: {},
      // 管点表单是否可见
      pointFormVisible: false,
      // 管点表单校验规则
      pointFormRules: {
        SCODE: [
          {required: true, message: "设施类别不能为空", trigger: "blur"}
        ],
        FEATURE: [
          {required: true, message: "设施名称不能为空", trigger: "blur"}
        ],
        DEEP: [
          {required: true, message: "埋深不能为空", trigger: "blur"}
        ],
        X: [
          {required: true, message: "X坐标不能为空", trigger: "blur"}
        ],
        Y: [
          {required: true, message: "Y坐标不能为空", trigger: "blur"}
        ],
        H: [
          {required: true, message: "高程不能为空", trigger: "blur"}
        ],
      },
      // 管点表单
      lineForm: {
        S_SCODE: '直线点',
        E_SCODE: '直线点',
        FLOW_D: 1,
      },
      // 管点表单是否可见
      lineFormVisible: false,
      // 管点表单校验规则
      lineFormRules: {
        S_POINT: [
          {required: true, message: "起点编号不能为空", trigger: "blur"}
        ],
        E_POINT: [
          {required: true, message: "终点编号不能为空", trigger: "blur"}
        ],
        D_S: [
          {required: true, message: "请选择管径", trigger: "blur"}
        ],
        MATERIAL: [
          {required: true, message: "请选择材质", trigger: "blur"}
        ],
        ROAD: [
          {required: true, message: "请输入所在道路", trigger: "blur"}
        ],
        S_SCODE: [
          {required: true, message: "请选择起点设施类别", trigger: "blur"}
        ],
        E_SCODE: [
          {required: true, message: "请选择终点设施类别", trigger: "blur"}
        ],
        S_DEEP: [
          {required: true, message: "请输入起点埋深", trigger: "blur"}
        ],
        E_DEEP: [
          {required: true, message: "请输入终点埋深", trigger: "blur"}
        ],
        FLOW_D: [
          {required: true, message: "请选择流向", trigger: "blur"}
        ],
      },
      // 图层初始化相关数据
      geomLayerData: {
        tenant: '',
        serviceUrl: '',
        pointParams: {},
        pointTableName: '',
        lineParams: {},
        lineTableName: '',
        getDictData: 'qtgis:func_get_dict_data',
        getMaxPointNum: 'qtgis:get_max_point_num',
        findLineFromPoint: 'qtgis:func_find_line_from_point',
        findPointById: 'qtgis:func_find_point_by_id',
        updateLineTopology: 'qtgis:func_update_line_topology',
        deletePointAfterLine: 'qtgis:func_delete_point_after_line',
      },
    }
  },
  methods: {
    handleMapLoaded(scene) {
      this.mapScene = scene

      // 添加地图放大缩小控件
      initSceneZoomControl(scene)

      // 添加地图图例控件
      this.legendControl = initSceneLegendControl(scene)

      // 添加地图场景要素图片
      initSceneImage(scene)

      this.initFeatureClickHandler()

      // 初始化图层数据
      this.getGisLayers(scene)
    },
    // 初始化管点、管线图层点击选中事件处理
    initFeatureClickHandler() {
      // =========初始化选中管点图层-BEGIN=========
      const lineJsonData = {
        type: 'FeatureCollection',
        features: [],
      };

      this.activePolylineLayer = new LineLayer({
        zIndex: 1000
      }).source(lineJsonData)
        .shape('line')
        .size(4)
        .color('#fcb268')
      // =========初始化选中管点图层-END=========

      // =========初始化选中管点图层-BEGIN=========
      const pointJsonData = {
        type: 'FeatureCollection',
        features: [],
      };

      this.activePointLayer = new PointLayer({
        zIndex: 1005
      }).source(pointJsonData)
        .shape('simple')
        .size(6)
        .color('#fcb268')
      // =========初始化选中管点图层-END=========
    },
    // 管线选中事件处理
    handleLineLayerClick(e) {
      const {lng, lat} = e.lngLat
      const viewParams = `tbl:${this.geomLayerData.lineTableName};pt:${lng} ${lat}`
      callSQLViewByWFS(this.geomLayerData.serviceUrl, this.geomLayerData.findLineFromPoint, viewParams, (data) => {
        if (data.features.length) {
          this.handlePointClose()
          this.handlePolylineClose()

          const line = data.features[0]
          this.lineForm = line.properties
          this.lineFormVisible = true
          this.editingFeature = line

          const lineJsonData = {
            type: 'FeatureCollection',
            features: [
              {
                type: 'Feature',
                properties: {},
                geometry: {
                  type: 'LineString',
                  coordinates: [line.geometry.coordinates[0]]
                },
              },
            ],
          };
          this.activePolylineLayer.setData(lineJsonData)
          this.activePolylineLayer.show()
          if (!this.activePolylineLayerAdded) {
            this.mapScene.addLayer(this.activePolylineLayer)
            this.activePolylineLayerAdded = true
          }
        }
      })
    },
    getGisLayers(scene) {
      const that = this
      this.mapScene.removeAllLayer()

      this.polylineLayer = undefined
      this.polylineLabelLayer = undefined
      this.pointLayerList = []
      this.layerTreeData = []
      this.defaultCheckTreeData = []

      let polylineLabelLoaded = false, pointLoaded = false

      const queryParams = {
        tableName: 'sys_gis_layer',
        pageNum: 1,
        pageSize: 999999
      }
      // 查询图层表数据
      findTableData(queryParams).then(res => {
        if (res.code === 200 && res.data && res.data.length) {
          this.geomLayerData.pointParams = res.data.filter(item => item.layer_type === 1)[0]
          this.geomLayerData.lineParams = res.data.filter(item => item.layer_type === 2)[0]
          this.geomLayerData.lineTableName = this.geomLayerData.lineParams.target_table
          this.geomLayerData.pointTableName = this.geomLayerData.pointParams.target_table
          this.geomLayerData.tenant = this.geomLayerData.pointParams.tenant_id
          this.geomLayerData.serviceUrl = this.geomLayerData.pointParams.service_url

          // 初始化字典数据
          this.initDictTypeOptions()

          // ============================================添加管线图层-BEGIN============================================
          const wmsUrl = this.geomLayerData.serviceUrl.replace('/ows', '/wms')
          const layerName = this.geomLayerData.lineParams.layer_prefix + ':' + that.geomLayerData.lineParams.layer_name
          const wmsLayerUrl = `${wmsUrl}?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&STYLES&LAYERS=${layerName}&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&WIDTH=521&HEIGHT=768&BBOX={bbox}`
          this.polylineLayer = drawWmsLayer(undefined, wmsLayerUrl, that.handleLineLayerClick)
          // ============================================添加管线图层-END============================================

          // ============================================添加管线-管径文字图层-BEGIN==========================================
          loadFeaturesByWFS(that.geomLayerData.lineParams.service_url, layerName, that.geomLayerData.lineTableName, (data) => {
            that.polylineLabelLayer = initLineLabelLayer(data)
          })

          // 管点图层加载完成
          document.addEventListener('initPolylineLabelLayer', () => {
            setTimeout(() => {
              polylineLabelLoaded = true
            }, 100)
          });
          // ============================================添加管线-管径文字图层-END============================================

          // ============================================添加管点图层-BEGIN============================================
          loadFeaturesByWFS(that.geomLayerData.pointParams.service_url, that.geomLayerData.pointParams.layer_prefix + ':' + that.geomLayerData.pointParams.layer_name, that.geomLayerData.pointTableName, (data) => {
            const {pointLayerList} = initPointLayer(data, (e) => {
              // ============================================管点图层点击事件处理-BEGIN============================================
              const viewParams = `tbl:${that.geomLayerData.pointTableName};id:${e.feature.properties.id}`
              callSQLViewByWFS(that.geomLayerData.pointParams.service_url, that.geomLayerData.findPointById, viewParams, (pointData) => {
                if (pointData.features.length) {
                  that.handlePointClose()
                  that.handlePolylineClose()

                  that.pointForm = pointData.features[0].properties
                  that.pointFormVisible = true

                  const pointJsonData = {
                    type: 'FeatureCollection',
                    features: [
                      {
                        type: 'Feature',
                        properties: {},
                        geometry: {
                          type: 'Point',
                          coordinates: e.feature.geometry.coordinates
                        },
                      },
                    ],
                  };
                  that.activePointLayer.setData(pointJsonData)
                  that.activePointLayer.show()
                  if (!that.activePointLayerAdded) {
                    that.mapScene.addLayer(that.activePointLayer)
                    that.activePointLayerAdded = true
                  }
                }
              })
              // ============================================管点图层点击事件处理-END============================================
            })

            that.pointLayerList = pointLayerList
          })

          // 管点图层加载完成
          document.addEventListener('initPointLayer', () => {
            setTimeout(() => {
              pointLoaded = true
            }, 100)
          });

          const timerCheckLoaded = setInterval(() => { // 管线管点图层都加载完成后，设置图层树
            if (polylineLabelLoaded && pointLoaded) {
              // 清除定时器
              clearInterval(timerCheckLoaded)

              initMapLayerTree(that.layerTreeData, that.polylineLayer, that.polylineLabelLayer, that.pointLayerList, (selectedTreeNodeKeys) => {
                this.$nextTick(() => {
                  // 图层添加到地图场景
                  scene.addLayer(that.polylineLayer)
                  scene.addLayer(that.polylineLabelLayer)
                  that.pointLayerList.forEach(item => scene.addLayer(item.target))

                  // 设置图层管理树默认选中节点
                  that.defaultCheckTreeData = selectedTreeNodeKeys
                  that.layerTreeLoading = false
                  that.$forceUpdate()
                })
              })
              that.initDrawPointTool(scene);
              that.initDrawPolylineTool(scene);
            }
          }, 50)
          // ============================================添加管点图层-END============================================
        }
      })
    },
    //初始化画点工具
    initDrawPointTool(scene){
      const that = this;
      const {serviceUrl, getMaxPointNum, pointParams} = that.geomLayerData
      const viewParams = `tbl:${pointParams.target_table}`
      // 初始化绘制工具
      this.drawPointTool = new DrawPoint(scene, {multiple: false});//禁止绘制多个

      // 启用绘制点模式
      this.drawPointTool.disable();

      // 监听绘制完成事件
      this.drawPointTool.on(DrawEvent.Change, (event) => {
        //当前点
        if(event[0] != undefined){
          let currentGeometry = event[0].geometry
          console.log('绘制点完成:', event[0].geometry);
          let maxnum = 0
          callSQLViewByWFS(serviceUrl, getMaxPointNum, viewParams, (data) => {
            if (data.features.length) {
              maxnum = data.features[0].properties.maxnum
            }
            const startNum = 'JS' + ('' + (maxnum + 1)).padStart(6, '0');
            that.pointForm = {
              X:currentGeometry.coordinates[0],
              Y:currentGeometry.coordinates[1]
            }
            that.pointForm.EXP_NO = startNum;
            // const strGeom = lineList[0].geometry.coordinates.map(item => item[0] + ' ' + item[1]).join(',')
            // that.lineForm.geom = `MULTILINESTRING((${strGeom}))`
            that.pointFormVisible = true
            that.drawPointTool.disable()
            that.isDrawingPoint = false;
            that.$forceUpdate()
          })  
        }
      });
    },
    // 初始化划线工具
    initDrawPolylineTool(scene) {
      const that = this
      // ============================================初始化画线工具-END============================================
      const {serviceUrl, getMaxPointNum, pointParams} = that.geomLayerData
      const viewParams = `tbl:${pointParams.target_table}`

      that.drawLineTool = new DrawLine(scene, {});

      // 默认禁用绘制功能
      that.drawLineTool.disable()

      // 监听绘制事件
      that.drawLineTool.on(DrawEvent.Change, (lineList) => {
        if (lineList && lineList.length) {
          // ==========查找起点、终点与现有管线的交点-BEGIN==========
          let startJoinPoint = {}, endJoinPoint = {}

          if (that.adsorbEnable) { // 吸附开关是否开启
            const pointCount = lineList[0].geometry.coordinates.length
            const lineStartPoint = lineList[0].geometry.coordinates[0]
            const lineEndPoint = lineList[0].geometry.coordinates[pointCount - 1]

            const searchPoints = []
            that.pointLayerList.forEach(pointLayer => {
              const pointSourceData = pointLayer.target.getSource().data.dataArray
              pointSourceData.forEach(pf => {
                searchPoints.push(pf)
              })
            })

            const radius = that.adsorbRange / 1000.0
            let findS = that.findNearestPoint(radius, lineStartPoint, searchPoints) // 查询距离起点最近的点
            let findE = that.findNearestPoint(radius, lineEndPoint, searchPoints) // 查询距离终点点最近的点
            // console.log(findS, findE)
            if (findS && !findE) { // 找到起点，没找到终点
              startJoinPoint.data = findS
            } else if (!findS && findE) { // 没找到起点，找到终点
              endJoinPoint.data = findE
            } else if (findS && findE) { // 找到起点和终点
              if (findS.id === findE.id) {
                // 起点和终点为同一个点，根据吸附方向来确定吸附到哪个点
                if (that.adsorbBeginning) {
                  startJoinPoint.data = findS
                } else {
                  endJoinPoint.data = findE
                }
              } else {
                // 起点和终点不是同一个点，分别赋值
                startJoinPoint.data = findS
                endJoinPoint.data = findE
              }
            }

            const newLineList = JSON.parse(JSON.stringify(lineList))
            // 吸附 ---> 修改绘制起点的坐标
            if (startJoinPoint.data) {
              newLineList[0].geometry.coordinates[0] = startJoinPoint.data.coordinates
            }

            // 吸附 ---> 修改绘制终点的坐标
            if (endJoinPoint.data) {
              newLineList[0].geometry.coordinates[pointCount - 1] = endJoinPoint.data.coordinates
            }

            that.drawLineTool.setData(newLineList)
          }

          // console.log('find,,,', startJoinPoint, endJoinPoint)
          // ==========查找起点、终点与现有管线的交点-END==========

          let maxnum = 0
          callSQLViewByWFS(serviceUrl, getMaxPointNum, viewParams, (data) => {
            if (data.features.length) {
              maxnum = data.features[0].properties.maxnum
            }

            const startNum = startJoinPoint.data ? startJoinPoint.data.EXP_NO : 'JS' + ('' + (maxnum + 1)).padStart(6, '0'),
              endNum = endJoinPoint.data ? endJoinPoint.data.EXP_NO : startJoinPoint.data ? 'JS' + ('' + (maxnum + 1)).padStart(6, '0') : 'JS' + ('' + (maxnum + 2)).padStart(6, '0')
            that.lineForm = {
              S_SCODE: startJoinPoint.data ? startJoinPoint.data.SCODE : '直线点',
              E_SCODE: endJoinPoint.data ? endJoinPoint.data.SCODE : '直线点',
              FLOW_D: 1,
            }
            that.lineForm.S_POINT = startNum
            that.lineForm.S_EXIST = startJoinPoint.data !== undefined ? 1 : 0
            that.lineForm.E_POINT = endNum
            that.lineForm.E_EXIST = endJoinPoint.data !== undefined ? 1 : 0
            const strGeom = lineList[0].geometry.coordinates.map(item => item[0] + ' ' + item[1]).join(',')
            that.lineForm.geom = `MULTILINESTRING((${strGeom}))`
            that.lineFormVisible = {}
            that.lineFormVisible = true
            that.drawLineTool.disable()
            that.$forceUpdate()
          })
        }
      });
      // ============================================初始化画线工具-END============================================
    },
    findNearestPoint(radius, targetPoint, pointList) {
      // console.log(radius, targetPoint, pointList)
      let result = null
      // 定义中心点和多个点
      // turf.point([longitude, latitude]),
      const centerPoint = turf.point(targetPoint); // 中心点坐标
      const points = [];
      pointList.forEach(pt => points.push(turf.point(pt.coordinates)))

      // 找到 radius 米范围内的点
      const nearbyPoints = points.filter(point => {
        const distance = turf.distance(centerPoint, point, {units: "kilometers"});
        return distance <= radius;
      });

      // 如果有多个点在范围内，找到最近的一个
      if (nearbyPoints.length > 0) {
        const nearestPoint = nearbyPoints.reduce((closest, point) => {
          const distance = turf.distance(centerPoint, point);
          return distance < turf.distance(centerPoint, closest) ? point : closest;
        });
        // console.log('最近的点:', nearestPoint);
        result = pointList.filter(pt => pt.coordinates.join(';') === nearestPoint.geometry.coordinates.join(';'))[0]
      } else {
        // console.log('没有在范围内的点');
      }

      return result
    },
    // 获取并设置字典数据
    getAndSetDictDataOptions(dictType) {
      const {serviceUrl, getDictData} = this.geomLayerData
      const viewParams = `dictType:${dictType}`
      callSQLViewByWFS(serviceUrl, getDictData, viewParams, (data) => {
        if (data.features.length) {
          const options = data.features.map(item => {
            return {label: item.properties.dict_label, value: item.properties.dict_label}
          })
          this.dictTypes[dictType] = options
        }
      })
    },
    // 初始化字典数据
    initDictTypeOptions() {
      Object.keys(this.dictTypes).forEach(key => {
        this.getAndSetDictDataOptions(key)
      })
    },
    // 开启绘制管线
    handleDrawLineClick() {
      if (!this.isDrawingLine && !this.isDrawingPoint) {
        this.drawLineTool.enable()
        this.isDrawingLine = true
      } else {
        this.$message.error('请先完成当前绘制')
      }
    },
    // 开启绘制管点
    handleDrawPointClick(){
      if (!this.isDrawingPoint && !this.isDrawingLine) {
        this.drawPointTool.enable()
        this.isDrawingPoint = true
      } else {
        this.$message.error('请先完成当前绘制')
      }
    },
    // 处理删除按钮事件
    handleDeleteClick() {
      const that = this
      const type = this.editingFeature.geometry.type === 'Point' ? 1 : 2
      const {S_POINT, E_POINT} = this.editingFeature.properties
      this.$modal.confirm('是否确认删除所选要素？').then(function () {
        const formData = {}
        formData.tableName = type === 1 ? that.geomLayerData.pointTableName : that.geomLayerData.lineTableName
        formData.id = that.editingFeature.properties.id
        return delTableData(formData);
      }).then(() => {
        if (type === 1) {
          that.handlePointClose()
        } else {
          // this.handlePolylineClose()
          // this.getGisLayers(this.mapScene)
          setTimeout(() => that.deleteNoUsePoints(S_POINT, E_POINT), 500)
        }
        that.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 删除管线后检查并删除不再使用的管点
    deleteNoUsePoints(S_POINT, E_POINT) {
      const {serviceUrl, deletePointAfterLine, lineTableName, pointTableName} = this.geomLayerData
      const viewParams = `lineTable:${lineTableName};pointTable:${pointTableName};sPoint:${S_POINT};ePoint:${E_POINT}`
      callSQLViewByWFS(serviceUrl, deletePointAfterLine, viewParams, (data) => {
        this.handlePolylineClose()
        this.getGisLayers(this.mapScene)
      })
    },
    // 切换图例图层显示/隐藏
    toggleLegendControl() {
      if (this.legendControlVisible) {
        this.legendControl.hide()
        this.legendControlVisible = false
      } else {
        this.legendControl.show()
        this.legendControlVisible = true
      }
    },
    // 处理图层树节点点击事件
    handleNodeChange(data, checked, indeterminate) {
      if (data.target) {
        if (checked) {
          data.target.show()
        } else {
          data.target.hide()
        }
      }
    },
    // 获取图层树节点图标
    getLayerNodeImage(data) {
      return require(`@/assets/gis-svg/` + data.icon)
    },
    // 保存管点数据
    saveGistPointInfo() {
      const tableName = this.geomLayerData.pointParams.target_table
      this.$refs["refPointForm"].validate(valid => {
          if (valid) {
            const formData = {}
            formData.tableType = 1
            formData.tableName = tableName
            formData.newRow = JSON.parse(JSON.stringify(this.pointForm))
            formData.id = this.pointForm.id
            formData.newRow.geom = `POINT(${formData.newRow.X} ${formData.newRow.Y})`
            delete formData.newRow.id
            delete formData.newRow.total
            delete formData.newRow.isActive // 删除AntV L7添加的属性
            delete formData.newRow.isDrag // 删除AntV L7添加的属性
            delete formData.newRow.isHover // 删除AntV L7添加的属性
            delete formData.newRow.isDraw // 删除AntV L7添加的属性
            delete formData.newRow.nodes // 删除AntV L7添加的属性
            delete formData.newRow.createTime // 删除AntV L7添加的属性
            if (formData.id != null && formData.id !== '') {
              delete formData.newRow.transform_geom
              formData.fields = Object.keys(formData.newRow)
              updatePointTableData(formData).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("修改成功");
                  this.handlePointClose()
                } else {
                  this.$modal.msgError(response.msg);
                }
              });
            } else {
              formData.newRow.transform_geom = formData.newRow.geom
              formData.fields = Object.keys(formData.newRow)
              addPointTableData(formData).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("新增成功");
                  this.handlePointClose()
                  this.getGisLayers(this.mapScene)
                } else {
                  this.$modal.msgError(response.msg);
                }
              });
            }
          }
        }
      );
    },
    // 关闭管点编辑窗口
    handlePointClose() {
      this.activePointLayer.hide()
      this.pointForm = {}
      this.pointFormVisible = false
      this.isDrawingPoint = false
      if (this.drawPointTool) {
        this.drawPointTool.clear()
      }

    },
    // 保存管线数据
    savePolylineData() {
      const pointTableName = this.geomLayerData.pointParams.target_table
      const lineTableName = this.geomLayerData.lineParams.target_table
      this.$refs["refLineForm"].validate(valid => {
          if (valid) {
            const formData = {}
            formData.tableType = 2
            formData.tableName = lineTableName
            formData.newRow = JSON.parse(JSON.stringify(this.lineForm))
            formData.id = this.lineForm.id
            formData.newRow.pointTable = pointTableName
            delete formData.newRow.id
            delete formData.newRow.total
            delete formData.newRow.isActive // 删除AntV L7添加的属性
            delete formData.newRow.isDrag // 删除AntV L7添加的属性
            delete formData.newRow.isHover // 删除AntV L7添加的属性
            delete formData.newRow.isDraw // 删除AntV L7添加的属性
            delete formData.newRow.nodes // 删除AntV L7添加的属性
            delete formData.newRow.createTime // 删除AntV L7添加的属性
            if (formData.id != null && formData.id !== '') {
              delete formData.newRow.transform_geom
              formData.fields = Object.keys(formData.newRow)
              updateLineTableData(formData).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("修改成功");
                  this.handlePolylineClose()
                } else {
                  this.$modal.msgError(response.msg);
                }
              });
            } else {
              formData.newRow.transform_geom = formData.newRow.geom
              formData.fields = Object.keys(formData.newRow)
              addLineTableData(formData).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("新增成功");
                  this.handlePolylineClose()
                  this.updateTransformGeomAndTopology(() => this.getGisLayers(this.mapScene))
                } else {
                  this.$modal.msgError(response.msg);
                }
              });
            }
          }
        }
      );
    },
    // 更新坐标和拓扑结构
    updateTransformGeomAndTopology(callback) {
      const {updateLineTopology, serviceUrl, lineTableName} = this.geomLayerData
      const viewParams = `tbl:${lineTableName};`
      callSQLViewByWFS(serviceUrl, updateLineTopology, viewParams, (data) => {
        callback()
      })
    },
    // 关闭管线编辑窗口
    handlePolylineClose() {
      this.activePolylineLayer.hide()
      this.lineForm = {}
      this.lineFormVisible = false
      this.editingFeature = undefined
      this.isDrawingLine = false
      if (this.drawLineTool) {
        this.drawLineTool.clear()
      }
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device'
    ]),
    getAvailableHeight() {
      return {height: (this.screenHeight - 70) + 'px'}
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 15px !important;
}
</style>
